package com.gpj.learn.rocketmq.filter;

import com.gpj.learn.rocketmq.CommonConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.MessageSelector;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;

/**
 * @className SQLFilterConsumer
 * @description
 *   需要在RocketMQ的broker配置中添加: enablePropertyFilter = true
 * @author GPJ
 * @date 2021/4/26 22:49
 * @version 1.0
 **/
@Slf4j
public class SQLFilterConsumer {
	public static void main(String[] args) {
		DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("FilterMeeageConsumerGroup");
		consumer.setNamesrvAddr(CommonConstants.ROCKETMQ_NAMESERVER_ADDR);

		try {
			consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_LAST_OFFSET);
			consumer.subscribe(CommonConstants.DEFAULT_TOPIC_NAME,
					MessageSelector.bySql("(TAGS is not null and TAGS = 'TagB') " +
							"and (mark is not null and mark > 3)"));
			consumer.registerMessageListener((MessageListenerConcurrently) (list, context) -> {
				for (MessageExt message : list) {
					log.info("接收到消息:{}", message);
				}
				return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
			});

			consumer.start();
			log.info("consumer starting...");
		} catch (MQClientException e) {
			e.printStackTrace();
		}

	}
}
